import config from './WebIMConfig';
import websdk from 'easemob-websdk';
import EventBus from '@src/util/eventBus'
import * as ImApi from 'src/api/ImApi'
import i18n from '@src/locales'
// 初始化IM SDK
let WebIM = {};
WebIM = window.WebIM = websdk;
WebIM.config = config;
WebIM.conn = new WebIM.connection({
  appKey: WebIM.config.appkey,
  isMultiLoginSessions: WebIM.config.isMultiLoginSessions,
  https: WebIM.config.https,
  isAutoLogin: true,
  heartBeatWait: WebIM.config.heartBeatWait,
  autoReconnectNumMax: WebIM.config.autoReconnectNumMax,
  autoReconnectInterval: WebIM.config.autoReconnectInterval,
  isStropheLog: WebIM.config.isStropheLog,
  delivery: WebIM.config.delivery,

  // 公有云 isHttpDNS 默认配置为true
  // isHttpDNS: WebIM.config.isHttpDNS,

  // 私有云设置，详细文档：http://docs-im.easemob.com/im/web/other/privatedeploy
  // isHttpDNS: false,
  // url: 'https://im-api-v2.easecdn.com/ws', // 设置为私有云的websocket server url
  // apiUrl: 'https://a1.easecdn.com', // 设置为私有云的rest server url
  url: WebIM.config.socketServer,
  apiUrl: WebIM.config.restServer,
});

// 注册监听回调
WebIM.conn.listen({
  onOpened(message){ // 连接成功回调
    console.info(message, '连接成功回调');
    // 登录或注册成功后 跳转到好友页面
    // const username = Vue.$store.state.login.username || localStorage.getItem("userInfo") && JSON.parse(localStorage.getItem("userInfo")).userId;
    // Vue.$store.dispatch("getLoginUserInfo", { userId: username });
    // const path = location.pathname.indexOf("login") !== -1 || location.pathname.indexOf("register") !== -1 ? "/contact" : location.pathname;
    // const redirectUrl = `${path}?username=${username}`;
    // Vue.$router.push({ path: redirectUrl });
  },
  onClosed(message){
    console.info(message, '连接关闭回调');
    // Vue.$router.push({ path: "/login" });
  }, // 连接关闭回调
  onTextMessage(message){
    // console.info('onTextMessage', message);
    const { id, from, type, time, data, mid} = message;
    let createTime = Number(time)
    let msg = {
      id,
      messageType: 'txt',
      messageContent: {
        msg : data
      },
      status: 2, // 未读
      sendType: 2,
      createTime,
      from,
      mid
    }
    // EventBus.$emit('addMessage', msg);
    type === 'chat' && ack(message);
  }, // 收到文本消息

  onPictureMessage(message){
    const { from, to, type, time } = message;
    const chatId = type !== 'chat' ? to : from;
    const typeMap = {
      chat: 'contact',
      groupchat: 'group',
      chatroom: 'chatroom'
    };
    type === 'chat' && ack(message);
  }, // 收到图片消息
  onFileMessage(message){
    console.info('onFileMessage', message);
    // const { from, to, type, time } = message;
    // const chatId = type !== 'chat' ? to : from;
    // const typeMap = {
    //   chat: 'contact',
    //   groupchat: 'group',
    //   chatroom: 'chatroom'
    // };
    const { id, from, type, data, mid, ext, filename} = message;
    let msg = {
      id,
      messageType: 'file',
      messageContent: {
        ext,
        filename
      },
      status: 2, // 未读
      sendType: 2,
      from,
      mid
    }
    // EventBus.$emit('addMessage', msg);
    type === 'chat' && ack(message);
  }, // 收到文件消息
  	// 接受自定义消息
	onCustomMessage: function ( message ) {
		console.log("onCustomMessage", message);
		const { id, from, type, time, ext,customEvent,customExts} = message;
		let msg = {
			id,
			messageType: customEvent,
			messageContent: {
				ext,
				customExts
			},
			status: 3, // 已读
			sendType: 1,
			createTime: time,
		}
		EventBus.$emit('addMessage', msg);
		type === "chat" && ack(message);
	},
  onRoster(message){
    console.info('onRoster', message);
  }, // 处理好友申请
  onOnline(){
    console.info('onOnline 网络已连接');
  }, // 本机网络连接成功
  onOffline(){
    console.info('onOffline 网络已断开');
  }, // 本机网络掉线
  onError(message){
    console.info('onError', message);
  }, // 失败回调
  onRecallMessage: message => {
    console.info('撤回消息', message);
    message.status = 'recall';
    message.msg = i18n.t('im.imChat.utils.tips1');
    // Vue.$store.commit("updateMessageStatus", message);
  },
  onBlacklistUpdate(list){ // 黑名单变动
    // 查询黑名单，将好友拉黑，将好友从黑名单移除都会回调这个函数，list则是黑名单现有的所有好友信息
    // 更新好友黑名单
    // console.info('黑名单变动', list);
    // let blackList = list;
    // Vue.$store.commit("updateBlackList", blackList);
  },
  onReceivedMessage(message){
    // console.info('onReceivedMessage', message);
    // Vue.$store.commit("updateMessageMid", message);
    // message.status = "sent";

    // Vue.$store.commit("updateMessageStatus", message);
  }, // 收到消息送达服务器回执

  onDeliveredMessage(message){
    console.info('onDeliveredMessage', message);
    // Vue.$store.commit('updateMessageStatus', message)
  }, // 收到消息送达客户端回执

  onReadMessage(message){
    // console.info('onReadMessage', message);
    // message.status = "read";
    // Vue.$store.commit("updateMessageStatus", message);
    // todo 更新会话消息的状态
    // EventBus.$emit('updateMessageStatus', message);
  }, // 收到消息已读回执
});

function ack(message){
  // let bodyId = message.id; // 需要发送已读回执的消息id
  // let msg = new WebIM.message('read', WebIM.conn.getUniqueId());
  // msg.set({
  //   id: bodyId,
  //   to: message.from
  // });
  // WebIM.conn.send(msg.body);
  // 更新我们自己服务器消息状态
  // "id" : "消息ID",
  // “status” : "消息状态（0-未发送；1-已送达；2-未读；3-已读）",
  // "conversationId" : "会话ID"
  // const params = {}
  // params.imId = message.mid
  // params.status = 3
  // params.conversationId = +localStorage.getItem('conversationId')
  // ImApi.editMessageInfo(params)
}

export default WebIM;
